/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.example;

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import org.apache.log4j.*;
import org.apache.log4j.spi.*;
import org.apache.log4j.helpers.Transform;

/**
 *
 * @author 
 */
public class textpaneAppender extends AppenderSkeleton {

    javax.swing.JTextPane jText = null;

    public textpaneAppender(Layout layout, javax.swing.JTextPane jText) {
        this.layout = layout;
        this.jText = jText;
    }

    public textpaneAppender(javax.swing.JTextPane jText) {
        this.layout = new org.apache.log4j.PatternLayout("%p [%t] %c  - %m%n");
        this.jText = jText;
    }

    public void setJText(javax.swing.JTextPane jText) {
        this.jText = jText;
    }

    protected void append(LoggingEvent event) {
        if (this.jText == null) {
            return;
        }
        this.subAppend(event);
    }

    public boolean requiresLayout() {
        return true;
    }

    public synchronized void close() {
        if (this.closed) {
            return;
        }
        this.closed = true;

    }

    public void subAppend(LoggingEvent event) {
        synchronized (jText) {
            Document doc = this.jText.getStyledDocument();
            SimpleAttributeSet set = new SimpleAttributeSet();
            String eventlevel = "known";
            if (event.getLevel().equals(Level.DEBUG)) {
                StyleConstants.setForeground(set, Color.black);
            } else if (event.getLevel().equals(Level.INFO)) {
                StyleConstants.setForeground(set, Color.BLACK);
            } else if (event.getLevel().equals(Level.WARN)) {
                StyleConstants.setForeground(set, Color.red);
            } else if (event.getLevel().equals(Level.ERROR)) {
                StyleConstants.setForeground(set, Color.red);
            } else if (event.getLevel().equals(Level.FATAL)) {
                StyleConstants.setForeground(set, Color.red);
            }

            StyleConstants.setBold(set, false);
            try {
                doc.insertString(doc.getLength(), this.layout.format(event), set);
                //this.jText.append(this.layout.format(event));
                /*String[] s = event.getThrowableStrRep();
                if (s != null) {
                    StyleConstants.setForeground(set, Color.red);
                    int len = s.length;
                    if (len > 0) {
                        for (int i = 1; i < len; i++) {
                            doc.insertString(doc.getLength(), s[i], set);
                        }
                    }
                    //doc.insertString(doc.getLength(), s, set);
                }*/
            } catch (BadLocationException ex) {
                java.util.logging.Logger.getLogger(textpaneAppender.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }

        }

    }
}
